package com.fqdf.framework.android.util;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.hardware.Camera;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.telephony.TelephonyManager;

import com.meituan.android.walle.WalleChannelReader;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class EnvUtil {

    private EnvUtil() {
        super();
    }

    /**
     * 是否调试模式
     *
     * @return
     */
    public static boolean isDebug(Context app) {
        return (app.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
    }

    /**
     * 检测网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetworkEnable(Context context) {
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                // 获取网络连接管理的对象
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    // 判断当前网络是否已经连接
//					if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
//					}
                }
            }
        } catch (Exception e) {
            LogUtil.i(EnvUtil.class, e.toString());
        }
        return false;
    }

    /**
     * 获取deviceId
     *
     * @return
     */
    public static String getDeviceId(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return CheckLogicUtil.isEmpty(tm.getDeviceId()) ? "" : tm.getDeviceId();
    }

    /**
     * 获取AndroidManifest.xml  meta-data 值
     *
     * @param context
     * @param name
     * @return
     */
    public static String getMetaDataValue(Context context, String name) {
        String value = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            if (applicationInfo != null && applicationInfo.metaData != null) {
                Object mDataValue = applicationInfo.metaData.get(name);
                if (null != mDataValue) {
                    value = String.valueOf(mDataValue);
                }
            }
        } catch (NameNotFoundException e) {
            throw new RuntimeException("Could not read the name in the manifest file.", e);
        }
        return value;
    }

    /**
     * 获取友盟渠道名
     *
     * @param context
     * @return
     */
//    public static String getUMChannelName(Context context) {
//        return getMetaDataValue(context, "UMENG_CHANNEL");
//    }
//
//    /**
//     * TalkingData 渠道名称
//     *
//     * @param context
//     * @return
//     */
//    public static String getTDChannelName(Context context) {
//        return getMetaDataValue(context, "TD_CHANNEL_ID");
//    }

    /**
     * 返回当前渠道包
     * @param context
     * @return
     */
    public static String getChannelName(Context context){
        return WalleChannelReader.getChannel(context.getApplicationContext(),Constants.DEFAULT_CHANNEL);
    }

    /**
     * 微信appID
     *
     * @param context
     * @return
     */
    public static String getWX_APP_ID(Context context) {
        return getMetaDataValue(context, "WX_APP_ID");
    }

    /**
     * 微信mchID
     *
     * @param context
     * @return
     */
    public static String getWX_MCH_ID(Context context) {
        return getMetaDataValue(context, "WX_MCH_ID");
    }

    /**
     * 区分不同APP版本
     *
     * @param context
     * @return
     */
    public static String getSOURCE_FOR(Context context) {
        return getMetaDataValue(context, "SOURCE_FOR");
    }

    /**
     * 获取应用版本名称
     *
     * @param context
     * @return
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 获取应用版本号
     *
     * @param context
     * @return
     */
    public static String getAppVersionCode(Context context) {
        String versionCode = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionCode = String.valueOf(packInfo.versionCode);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取手机系统版本
     *
     * @param context
     * @return
     */
    public static String getPhoneSysVersion(Context context) {
        String operatingSystem = "";
        operatingSystem = android.os.Build.VERSION.RELEASE;
        try {
            operatingSystem = URLEncoder.encode(operatingSystem, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return operatingSystem;
    }


    /**
     * 获取手机型号
     *
     * @param context
     * @return
     */
    public static String getPhoneType(Context context) {
        String phoneModel = "";
        phoneModel = android.os.Build.MODEL;
        try {
            phoneModel = URLEncoder.encode(phoneModel, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return phoneModel;
    }

    /**
     * 判断是否url属于router格式
     *
     * @param url url资源
     * @return true说明url是router格式，false说明url不是router格式
     */
    public static boolean isGofunRouter(String url) {
        if (CheckLogicUtil.isEmpty(url)) {
            return false;
        }
        return "gofun".equals(Uri.parse(url).getScheme());
    }

    /**
     * 判断是否uri属于router格式
     *
     * @param uri uri资源定位符
     * @return true说明uri是router格式，false说明uri不是router格式
     */
    public static boolean isGofunRouter(Uri uri) {
        if (uri == null) {
            return false;
        }
        return "gofun".equals(uri.getScheme());
    }

    /**
     * 检测
     *
     * @param context
     * @return
     */
    public static boolean CheckDeviceIDS(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        String device_ids = telephonyManager.getDeviceId();
        String[] known_device_ids = {"000000000000000"}; // 默认ID

        for (String know_deviceid : known_device_ids) {
            if (know_deviceid.equalsIgnoreCase(device_ids)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取位置服务是否开启
     *
     * @param context
     * @return
     */
    public static boolean getLocationService(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        return false;
    }

    /**
     * 是否为Gofun版本
     *
     * @return
     */
    public static boolean isGofun(Context context) {
        return EnvUtil.getSOURCE_FOR(context).equals("gofun");
    }

    /**
     * 是否为川交版本
     *
     * @return
     */
    public static boolean isChuanjiao(Context context) {
        return EnvUtil.getSOURCE_FOR(context).equals("chuanjiao");
    }

    /**
     * 是否有前置摄像头
     *
     * @return
     */
    public static boolean hasFrontCamera() {
        int cameraCount = Camera.getNumberOfCameras();
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                return true;
            }
        }

        return false;
    }

}